package com.tiorb.socketlibrary;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.tiorb.socketlibrary.model.MsgBean;
import com.xuhao.didi.core.protocol.IReaderProtocol;
import com.xuhao.didi.socket.client.impl.client.action.ActionDispatcher;
import com.xuhao.didi.socket.client.sdk.OkSocket;
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo;
import com.xuhao.didi.socket.client.sdk.client.OkSocketOptions;
import com.xuhao.didi.socket.client.sdk.client.connection.IConnectionManager;
import com.xuhao.didi.socket.client.sdk.client.connection.NoneReconnect;

import java.nio.ByteOrder;

public class SocketConnect {
    private static final String TAG = "SocketConnect";
    static SocketConnect socketConnect;
    Context mContext;
    ConnectionInfo connectionInfo;
    IConnectionManager manager;
    //获得当前连接通道的参配对象
    OkSocketOptions options;
    //基于当前参配对象构建一个参配建造者类
    OkSocketOptions.Builder builder;
    String ip = "";
    int port = -1;


    public void setAddress(String p1, int p2) {
        ip = p1;
        port = p2;
    }

    public SocketConnect(Context mContext) {
        this.mContext = mContext;
    }

    public void initSocket() {
        if (TextUtils.isEmpty(ip) || port == -1) {
            Toast.makeText(mContext, "IP和端口不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        Log.d(TAG, "initSocket:ip = " + ip + " ,port = " + port);
        final Handler handler = new Handler(Looper.getMainLooper());
        connectionInfo = new ConnectionInfo(ip, port);
        builder = new OkSocketOptions.Builder();
        builder.setReaderProtocol(new IReaderProtocol() {
            @Override
            public int getHeaderLength() {
                return 3;
            }

            @Override
            public int getBodyLength(byte[] header, ByteOrder byteOrder) {
                return 9;
            }
        }).setCallbackThreadModeToken(new OkSocketOptions.ThreadModeToken() {
            @Override
            public void handleCallbackEvent(ActionDispatcher.ActionRunnable actionRunnable) {
                handler.post(actionRunnable);
            }
        }).setReconnectionManager(new NoneReconnect());
        manager = OkSocket.open(connectionInfo).option(builder.build());
        manager.registerReceiver(new SocketAdapter());
    }

    public void send(String msg) {
        if (manager != null) {
            manager.send(new MsgBean(msg));
        }
    }

    public void Connect() {
        if (manager != null) {
            manager.connect();
        }
    }

    public boolean isConnected() {
        if (manager != null) {
            return manager.isConnect();
        } else {
            return false;
        }
    }

    public void disConnect() {
        if (manager != null) {
            manager.disconnect();
        }
    }
}
